package com.lilihub.miaosha.exception;

import com.lilihub.miaosha.common.CodeMsg;
import com.lilihub.miaosha.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;

/**
 * @BelongsProject: miaosha2
 * @BelongsPackage: com.lilihub.miaosha.exception
 * @Author: LiYing
 * @CreateTime: 2021-04-26 14:07
 * @Description:
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request,Exception e){

        e.printStackTrace();

        if (e instanceof GlobalException){

            GlobalException exception = (GlobalException) e;

            CodeMsg cm = exception.getCm();

            return Result.error(cm);

        }else if(e instanceof BindException){

            BindException exception = (BindException) e;

            String message = exception.getMessage();

            return Result.error(CodeMsg.BIND_ERROR.fillArgs(message));

        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }

}
